package commons.base.http.client;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.concurrent.FutureCallback;

/**
 * 线程池异步HTTPCLIENT
 * @author Administrator
 *
 */
public class ThreadPoolHttpClient extends AbstractHttpClient {

	private ExecutorService executorService;
	
	public ThreadPoolHttpClient(){
		this(Runtime.getRuntime().availableProcessors());
	}
	
	public ThreadPoolHttpClient(int threadCount) {
		super(new HttpClientFactory());
		executorService = Executors.newFixedThreadPool(threadCount);
	}
	
	public void execute(final HttpUriRequest request, final FutureCallback<Content> callback){
		executorService.submit(new Runnable() {
			@Override
			public void run() {
				try {
					Content result = httpClient.execute(request, new ResponseHandler<Content>(){
						@Override
						public Content handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
							return Content.get(response);
						}
					});
					callback.completed(result);
				} catch (Exception e) {
					callback.failed(e);
				}
			}
		});
	}
	
	@Override
	public void shutdown() throws IOException{
		if(executorService != null){
			executorService.shutdownNow();
		}
		super.shutdown();
	}

}
